"""
Unified decorators for component registration.

This module provides a consistent interface for registering components
using the base Registry system.
"""

from typing import Optional, Callable, TypeVar, Union, overload
from .base import Registry
import inspect

C = TypeVar("C")


def create_component_decorator(
    registry: Registry,
    default_name_prefix: Optional[str] = None,
):
    """Factory function to create component-specific decorators using base Registry."""

    @overload
    def decorator(name_or_cls: str) -> Callable[[type[C]], type[C]]: ...

    @overload
    def decorator(name_or_cls: type[C]) -> type[C]: ...

    def decorator(
        name_or_cls: Union[str, type[C], None] = None, **kwargs
    ) -> Union[Callable[[type[C]], type[C]], type[C]]:
        """Component registration decorator using base Registry."""

        # Handle direct class decoration: @decorator
        if inspect.isclass(name_or_cls):
            cls = name_or_cls
            name = (
                default_name_prefix + cls.__name__
                if default_name_prefix
                else cls.__name__
            )
            return registry.register(name)(cls)

        # Handle named decoration: @decorator("name") or @decorator()
        def inner_decorator(cls: type[C]) -> type[C]:
            if isinstance(name_or_cls, str):
                name = name_or_cls
            else:
                name = (
                    default_name_prefix + cls.__name__
                    if default_name_prefix
                    else cls.__name__
                )

            return registry.register(name)(cls)

        return inner_decorator

    return decorator


# Backward compatibility function
def register_component(
    name: str, registry: Optional[Registry] = None, **kwargs
):
    """
    Backward compatible component registration decorator.

    This function provides compatibility with the old component_registry
    decorator interface while using the new base registry system.
    """
    # Use global registry if none specified
    if registry is None:
        from .instances import Components as global_registry

        registry_c = global_registry

    else:
        registry_c = registry

    return registry_c.register(name_or_cls=name)
